package com.welink.cmp.gatewayimpl.topotree;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.welink.cmp.convertor.GenericConvertor;
import com.welink.cmp.dao.metadata.HostDaoService;
import com.welink.cmp.dao.metadata.SwitchDaoService;
import com.welink.cmp.dao.metadata.dataobject.HostDO;
import com.welink.cmp.dao.metadata.dataobject.SwitchDO;
import com.welink.cmp.dao.tree.DeviceTopologyDaoService;
import com.welink.cmp.dao.tree.dataobejct.DeviceTopologyTreeDO;
import com.welink.cmp.domain.metadata.Host;
import com.welink.cmp.domain.metadata.Switch;
import com.welink.cmp.domain.topotree.IDeviceTopoGateway;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author yanwei li create  2024-06-04 13:03
 */
@Primary
@Service
public class DeviceTopoTreeGatewayImpl implements IDeviceTopoGateway {

    @Resource
    private DeviceTopologyDaoService daoService;

    @Resource
    private SwitchDaoService switchDaoService;
    @Resource
    private HostDaoService hostDaoService;

    /**
     * 获取下绑定的交换机
     *
     * @param name
     * @return
     */
    @Override
    public List<Switch> getSwitchNodes(String name) {
        final List<String> nodesDeviceNames = getNodesDeviceNames(name);
        if (CollectionUtils.isEmpty(nodesDeviceNames)){
            return Collections.EMPTY_LIST;
        }
        final List<SwitchDO> switchDOList = switchDaoService.getListByName(nodesDeviceNames);

        return GenericConvertor.toDOList(switchDOList,Switch.class);
    }

    /**
     * 获取下绑定的主机
     *
     * @param name
     * @return
     */
    @Override
    public List<Host> getHostNodes(String name) {
        final List<String> nodesDeviceNames = getNodesDeviceNames(name);
        if (CollectionUtils.isEmpty(nodesDeviceNames)){
            return Collections.EMPTY_LIST;
        }
        final List<HostDO> hostDOLists = hostDaoService.getListByName(nodesDeviceNames);

        return GenericConvertor.toDOList(hostDOLists,Host.class);
    }

    /**
     *
     * @param localName
     * @return
     */
    private List<String> getNodesDeviceNames(String localName){
        LambdaQueryWrapper<DeviceTopologyTreeDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(DeviceTopologyTreeDO::getLocalDevice,localName)
                .eq(DeviceTopologyTreeDO::getStatus,"1");
        final List<DeviceTopologyTreeDO> topoList = this.daoService.list(wrapper);
        if (CollectionUtils.isEmpty(topoList)) {
            return Collections.EMPTY_LIST;
        }
        final List<String> names = topoList.stream().map(DeviceTopologyTreeDO::getLocalDevice).collect(Collectors.toList());

        return names;
    }


}
